import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: null,
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  async login({ commit }, userInfo) {
    try {
      const { username, password } = userInfo
      const response = await login({ username: username.trim(), password })
      const { data } = response
      
      commit('SET_TOKEN', data.token)
      if (data.userInfo) {
        commit('SET_USER_INFO', data.userInfo)
        commit('SET_NAME', data.userInfo.username)
        commit('SET_AVATAR', data.userInfo.avatar)
      }
      
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  },

  async getInfo({ commit, state }) {
    try {
      const response = await getInfo(state.token)
      const { data } = response

      if (!data) {
        return Promise.reject('Verification failed, please Login again.')
      }

      const { roles, username, avatar } = data
      
      commit('SET_USER_INFO', data)
      commit('SET_NAME', username)
      commit('SET_AVATAR', avatar)
      commit('SET_ROLES', roles)
      
      return Promise.resolve(data)
    } catch (error) {
      return Promise.reject(error)
    }
  },

  async logout({ commit, state }) {
    try {
      await logout(state.token)
      removeToken()
      resetRouter()
      commit('RESET_STATE')
      return Promise.resolve()
    } catch (error) {
      return Promise.reject(error)
    }
  },

  resetToken({ commit }) {
    removeToken()
    commit('RESET_STATE')
    return Promise.resolve()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}